import { observable, configure, action, computed } from 'mobx';
import axios from 'axios'

configure({ enforceActions: 'observed' });

const BUTTON_TEXT_DEFAULT = '摘苹果'
const BUTTON_TEXT_PICKING = '正在采摘...'

const URL_PICKING = 'https://hacker-news.firebaseio.com/v0/jobstories.json'

class AppleBasketStore {
    @observable apples = []
    @observable isPicking = false

    @computed get existApples() {
        return this.apples.filter(apple => apple.isEaten === false)
    }

    @computed get numberOfExistingApples() {
        return this.apples.filter(apple => apple.isEaten === false).length
    }

    @computed get weightOfExistingApples() {
        return this.apples.filter(apple => apple.isEaten === false).reduce((total, apple) => { return total += apple.weight }, 0)
    }

    @computed get numberOfEatenApples() {
        return this.apples.filter(apple => apple.isEaten === true).length
    }

    @computed get weightOfEatenApples() {
        return this.apples.filter(apple => apple.isEaten === true).reduce((total, apple) => { return total += apple.weight }, 0)
    }

    @computed get buttonText() {
        if (this.isPicking) {
            return BUTTON_TEXT_PICKING
        }
        return BUTTON_TEXT_DEFAULT
    }

    @action.bound eatApple = (appleId) => {
        for (let apple of this.apples) {
            if (apple.id === appleId) {
                apple.isEaten = true
                break
            }
        }
    }

    @action.bound pickApple = () => {
        if (this.isPicking) {
            return
        }
        this.isPicking = true
        axios.get(URL_PICKING).then(action((res) => {
            this.isPicking = false;
            this.apples.push({
                id: Math.floor(Math.random() * 1000),
                weight: Math.floor(200 + Math.random() * 50),
                isEaten: false
            });
        }))
    }
}
const appleBasket = new AppleBasketStore();
export default appleBasket;